package com.k2data.example;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StringInitializer extends ChannelInitializer<SocketChannel> {
    public static final Logger LOG = LoggerFactory.getLogger(StringInitializer.class);

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        byte[] dilimiter = "()".getBytes(CharsetUtil.UTF_8);
        byte[] dilimiter2 = ")".getBytes(CharsetUtil.UTF_8);
        ByteBuf[] byteBufs = new ByteBuf[2];
        byteBufs[0]=Unpooled.copiedBuffer(dilimiter);
        byteBufs[1]=Unpooled.copiedBuffer(dilimiter2);
        // tail is ("\n") split decoder
        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(10000, byteBufs));

        // string decoder and encoder
        pipeline.addLast("decoder", new StringDecoder());
        pipeline.addLast("encoder", new StringEncoder());
        // my Handler
        pipeline.addLast("handler", new StringHandler());
    }
}